import { defineStore } from "pinia";
import { StoreNames } from "@/tuniao-ui/store/storeName";
import { getStorage, setStorage, removeStorage, toast} from "@/tuniao-ui/utils";
import { ResultEnum } from "@/enums/httpEnum";
import { login, refreshToken, getMemberInfo } from "@/api/user";
import store from "@/tuniao-ui/store";
import {
  ACCESS_TOKEN,
  REFRESH_ACCESS_TOKEN,
  CURRENT_USER,
} from "../mutation-types";

export interface IUserState {
  id: number;
  token: string;
  refreshToken: string;
  memberName: string;
  memberNo: string;
  nickname: string;
  avatar: string;
  sex: number;
  mobile: string;
  status: number;
  info: any;
}

export const useUserStore = defineStore(StoreNames.SYSTEM_USER, {
  state: (): IUserState => ({
    id: 0,
    token: "",
    refreshToken: "",
    memberName: "",
    memberNo: "",
    nickname: "",
    sex: 0,
    mobile: "",
    status: 0,
    avatar: "",
    info: {},
  }),
  getters: {
    getId(): number {
      return this.id;
    },
    getToken(): string {
      return this.token;
    },
    getRefreshToken(): string {
      return this.refreshToken;
    },
    getAvatar(): string {
      return this.avatar;
    },
    getMemberName(): string {
      return this.memberName;
    },
    getMemberNo(): string {
      return this.memberNo;
    },
    getMobile(): string {
      return this.mobile;
    },
    getNickname(): string {
      return this.nickname;
    },
    getUserInfo(): object {
      return this.info;
    },
  },
  actions: {
    setId(id: number) {
      this.id = id;
    },
    setToken(token: string) {
      this.token = token;
    },
    setRefreshToken(refreshToken: string) {
      this.refreshToken = refreshToken;
    },
    setAvatar(avatar: string) {
      this.avatar = avatar;
    },
    setUserInfo(info: any) {
      this.memberName = info.memberName;
      this.memberNo = info.memberNo;
      this.nickname = info.nickname;
      this.sex = info.sex;
      this.status = info.status;
      this.mobile = info.mobile;

      this.info = info;
    },
    // 判断登录状态
    isLogin() {
      const token = getStorage(ACCESS_TOKEN);
      if (!token) {
        // 如果token不存在 但是刷新token存在 可以无感刷新登录
        const refreshToken = getStorage(REFRESH_ACCESS_TOKEN);
        return refreshToken ? true : false;
      }
      return true;
    },
    // 登录
    async login(userInfo: any) {
      try {
        const response = await login(userInfo);
        const { result, code } = response;
        if (code === ResultEnum.SUCCESS) {
          const ex = 2 * 60 * 60; // 用户token过期时间 2小时
          //const ex = 15; // 用户token过期时间 2小时
          const refershEx = 7 * 24 * 60 * 60; // 刷新token过期时间 7天
          setStorage(ACCESS_TOKEN, result.token, ex);
          setStorage(REFRESH_ACCESS_TOKEN, result.refreshToken, refershEx);
          this.setId(result.member.id);
          this.setToken(result.token);
          this.setRefreshToken(result.refreshToken);
          this.setUserInfo(result.member);
          //this.setAvatar("https://xinlong-shop.oss-cn-beijing.aliyuncs.com/goods/20221219/1391c21c-1bbe-47a7-ae32-1297d729816b.JPG");
        }
        return Promise.resolve(response);
      } catch (e) {
        return Promise.reject(e);
      }
    },
    // 获取用户信息
    GetInfo() {
      const that = this;
      let params = { memberId: that.getId };
      return new Promise((resolve, reject) => {
        getMemberInfo(params)
          .then((res) => {
            const result = res.result;
            //console.log(result);
            // login和info公用setUserInfo方法  可以把login的换掉，多一些set函数
            that.setUserInfo(result);
            if (result.status != 0) {
              toast({ title: "账号已被封禁",icon:'error'});
              this.logout();
            }
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },
    RefreshToken() {
      const that = this;
      const params = {
        userName: that.getMemberNo, // 后端是用memberNo来生成token的  所以这里用户名实际上传递的是memberNo
        refreshToken: that.getRefreshToken,
      };
      return new Promise((resolve, reject) => {
        refreshToken(params)
          .then((res) => {
            const result = res.result;
            const ex = 2 * 60 * 60; // 用户token过期时间 2小时
            //const ex = 15;
            setStorage(ACCESS_TOKEN, result, ex);
            //that.setToken(result);
            resolve(res);
          })
          .catch((error: any) => {
            reject(error);
          });
      });
    },
    // 登出
    async logout() {
      this.setUserInfo({});
      removeStorage(ACCESS_TOKEN);
      removeStorage(CURRENT_USER);
      removeStorage(REFRESH_ACCESS_TOKEN);
      return Promise.resolve("");
    },
  },
});

// Need to be used outside the setup
export function useUserStoreWidthOut() {
  return useUserStore(store);
}
